import { fetch } from 'plugins/axios'
import { downExcel } from 'plugins/common'

export function loadFilters ({state, commit}) {
  return new Promise((resolve, reject) => {
    fetch('/project/pubproject_filters/', {}).then((response) => {
      commit('filterSuccess', response)
      resolve()
    }).catch((error) => {
      console.log(error)
    })
  })
}

export function loadHeaders ({state, commit}) {
  return new Promise((resolve, reject) => {
    fetch('/getmodels/', {
      appname: 'project',
      modelname: 'Project'
    }).then((response) => {
      commit('headerSuccess', response)
      resolve()
    }).catch((error) => {
      state.etext = error.response
    })
  })
}

export function loadTable ({state, commit}) {
  return new Promise((resolve, reject) => {
    state.loading = true
    const {sortBy, descending, page, rowsPerPage} = state.serverPagination
    let ordering = descending ? '-' + sortBy : sortBy
    fetch('/project_for_publish/', {
      offset: (page - 1) * rowsPerPage,
      limit: rowsPerPage,
      ordering,
      search: state.search,
      env: state.env.value
    }).then((response) => {
      commit('loadTableSuccess', response)
      resolve()
    }).catch((error) => {
      state.etext = error.response
    })
  })
}

export function fileDownload ({state}) {
  downExcel(state.columns, state.tableData)
}
